import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:talk/commponets/ItemView.dart';
import 'package:talk/db/User.dart';
import 'package:talk/pages/my/model/UserModel.dart';

import '../../api/UserApi.dart';
import '../../api/dio/DioClient.dart';
import '../../home/AppLocale.dart';
import '../../res/gaps.dart';
import '../../routers/fluro_navigator.dart';
import '../../src/utils/theme_utils.dart';
import '../../tools/widgets/load_image.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/toast_utils.dart';
import '../add/x_add_router.dart';
import '../home/widgets/goods_add_menu.dart';
import '../login/login_router.dart';
import '../my/orders.dart';
import '../my/setting_router.dart';
import '../my/x_user_router.dart';

class UserPage extends StatefulWidget {
  const UserPage({
    super.key,
    this.isAccessibilityTest = false,
  });

  final bool isAccessibilityTest;

  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> with WidgetsBindingObserver {
  UserModel? _UserModel;
  late int _userId;
  final UserApi _userApi = UserApi();
  bool _isCurrentPage = true;
  // 添加时间戳跟踪最后一次刷新时间，避免频繁刷新
  DateTime? _lastRefreshTime;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _fetchData();
    // 启动周期性检查
    _startPeriodicCheck();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  // 启动周期性检查页面可见性
  void _startPeriodicCheck() {
    // 每300毫秒检查一次页面可见性
    Future.delayed(const Duration(milliseconds: 300), () {
      if (mounted) {
        _checkIfPageIsVisible();
        _startPeriodicCheck();
      }
    });
  }

  // 检查页面是否可见并刷新数据
  void _checkIfPageIsVisible() {
    final isVisible = ModalRoute.of(context)?.isCurrent ?? false;

    if (isVisible && !_isCurrentPage) {
      // 确保两次刷新间隔至少500毫秒，避免性能问题
      final now = DateTime.now();
      if (_lastRefreshTime == null ||
          now.difference(_lastRefreshTime!).inMilliseconds > 500) {
        _fetchData();
        _lastRefreshTime = now;
      }
    }

    _isCurrentPage = isVisible;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      _fetchData();
    }
  }

  // 页面重新构建时检查可见性
  @override
  void didUpdateWidget(covariant UserPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    _checkIfPageIsVisible();
  }

  Future<void> _fetchData() async {
    try {
      final response = await _userApi.userData();
      if (response.code == 200) {
        setState(() {
          _UserModel = UserModel.fromJson(response.data);
          if (_UserModel != null) {
            _userId = _UserModel!.userId!;
          }
        });
      } else {
        Toast.show("获取数据异常: ${response.code}");
      }
    } catch (e) {
      Toast.show("获取数据失败...");
    }
  }

  Future<void> _logout() async {
    try {
      final response = await _userApi.logout();
      if (response.code == 200) {
        setState(() {
          _UserModel = null;
        });
        NavigatorUtils.push(context, LoginRouter.loginPage);
      } else {
        Toast.show("退出失败: ${response.code}");
      }
    } catch (e) {
      Toast.show("退出出错: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        _isCurrentPage = false;
        return true;
      },
      child: Scaffold(
        appBar: MyAppBar(
          title: "",
          isBack: false,
        ),
        body: Container(
            child: Column(
              children: [
                InkWell(
                  onTap: () {
                    _isCurrentPage = false;
                    if (_UserModel == null) {
                      NavigatorUtils.push(context, LoginRouter.loginPage);
                    } else {
                      final deviceJson = json.encode(_UserModel!.toJson());
                      final encoded = Uri.encodeComponent(deviceJson);

                      NavigatorUtils.push(
                        context,
                        '${XUserRouter.userInfoPage}?userId=$_userId&userModel=$encoded',
                      );
                    }
                  },
                  child: Container(
                    padding: const EdgeInsets.only(
                        top: 20, left: 20, right: 40, bottom: 20
                    ),
                    decoration: const BoxDecoration(
                        color: Colors.transparent
                    ),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        ClipOval(
                          child: Image.network(
                            _UserModel?.avatar?.isNotEmpty == true
                                ? '${DioClient.baseUrl}${_UserModel!.avatar}'
                                : 'http://43.139.39.5:82/pho/face/weizhi.png',
                            width: 60,
                            height: 60,
                          ),
                        ),
                        Expanded(
                            child: Container(
                              height: 50,
                              margin: const EdgeInsets.only(left: 10, right: 10),
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    _UserModel?.userName ?? "登录/注册",
                                    style: const TextStyle(
                                        color: Color(0xFF333333),
                                        fontSize: 15,
                                        fontWeight: FontWeight.bold),
                                  ),
                                  Text(
                                    _UserModel?.phonenumber ?? "点击登录/注册",
                                    style: const TextStyle(color: Color(0xFF999999), fontSize: 12),
                                  ),
                                ],
                              ),
                            )),
                        const Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.grey,
                          size: 14,
                        )
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 20,),
                ItemView(
                  width: 360,
                  height: 60,
                  leftPadding: 20,
                  rightPadding: 20,
                  leftWidget: Row(
                    children: [
                      Image.asset("images/images/my/s1.png", width: 24),
                      const SizedBox(width: 10),
                      Text(AppLocale.text('my_guanyuwomen')),
                    ],
                  ),
                  borderRadius: 8,
                  onTap: () {
                    // _isCurrentPage = false;

                    NavigatorUtils.push(
                      context,
                      '${XUserRouter.userAbout}',
                    );

                  },
                ),



                // ItemView(
                //   width: 360,
                //   height: 60,
                //   leftPadding: 18,
                //   rightPadding: 20,
                //   leftWidget: Row(
                //     children: [
                //       Image.asset("images/images/my/s2.png", width: 24),
                //       const SizedBox(width: 10),
                //       const Text(""
                //           "客服中心"),
                //     ],
                //   ),
                //   borderRadius: 8,
                //   onTap: () {
                //     // _isCurrentPage = false;
                //     // NavigatorUtils.push(context, SettingRouter.callPage);
                //   },
                // ),
                // ItemView(
                //   width: 360,
                //   height: 60,
                //   leftPadding: 20,
                //   rightPadding: 20,
                //   leftWidget: Row(
                //     children: [
                //       Image.asset("images/images/my/s3.png", width: 24),
                //       const SizedBox(width: 10),
                //       const Text("帮助与反馈"),
                //     ],
                //   ),
                //   borderRadius: 8,
                //   onTap: () {
                //     // _isCurrentPage = false;
                //     // NavigatorUtils.push(context, SettingRouter.accountManagerPage);
                //
                //
                //
                //     NavigatorUtils.push(
                //       context,
                //       '${SettingRouter.settingPage}',
                //     );
                //
                //
                //   },
                // ),



                const SizedBox(height: 20,),
                ItemView(
                  width: 360,
                  height: 60,
                  leftPadding: 20,
                  rightPadding: 20,
                  leftWidget: Row(
                    children: [
                      Image.asset("images/images/my/s4.png", width: 24),
                      const SizedBox(width: 10),
                      Text(AppLocale.text('my_xitongshezhi')),
                    ],
                  ),
                  borderRadius: 8,
                  onTap: () {
                    // _isCurrentPage = false;


                    NavigatorUtils.push(
                      context,
                      '${XUserRouter.userSystem}',
                    );

                  },
                ),

                const SizedBox(height: 20,),


                // ItemView(
                //   width: 360,
                //   height: 60,
                //   leftPadding: 20,
                //   rightPadding: 20,
                //   leftWidget: Row(
                //     children: [
                //       Image.asset("images/images/my/s3.png", width: 24),
                //       const SizedBox(width: 10),
                //       const Text("退出"),
                //     ],
                //   ),
                //   borderRadius: 8,
                //   onTap: () {
                //     _logout();
                //   },
                // ),







              ],
            )),
      ),
    );
  }
}
